package jmine.tec.datadigester.web.pages.importacao;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import jmine.tec.executionlog.domain.ExecutionLog;

import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.resource.ResourceStreamNotFoundException;
import org.apache.wicket.util.time.Time;

import bancosys.tec.persist.controller.PersistenceEnabledController;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * {@link IResourceStream} para download de arquivos de {@link ExecutionLog}.
 * 
 * @author Rafael Volpato
 * @date Dec 9, 2010
 */
public class ExecutionLogResourceStream implements IResourceStream {

    private final Long executionLogId;

    private final Time time = Time.now();

    private Locale locale;

    private PersistenceEnabledController controller;

    /**
     * Construtor.
     * 
     * @param executionLogId executionLogId
     * @param controller controller
     */
    public ExecutionLogResourceStream(Long executionLogId, PersistenceEnabledController controller) {
        this.executionLogId = executionLogId;
        this.controller = controller;
    }

    /**
     * {@inheritDoc}
     */
    public Time lastModifiedTime() {
        return this.time;
    }

    /**
     * {@inheritDoc}
     */
    public String getContentType() {
        return "application/octet-stream";
    }

    /**
     * {@inheritDoc}
     */
    public long length() {
        return -1;
    }

    /**
     * {@inheritDoc}
     */
    public InputStream getInputStream() throws ResourceStreamNotFoundException {
        try {
            ExecutionLog executionLog = this.controller.getDAOFactory().getGenericDAO(ExecutionLog.class).findByPk(this.executionLogId);
            return executionLog.getContent();
        } catch (BeanNotFoundException e) {
            throw new ResourceStreamNotFoundException(e);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void close() throws IOException {

    }

    /**
     * @return the locale
     */
    public Locale getLocale() {
        return this.locale;
    }

    /**
     * @param locale the locale to set
     */
    public void setLocale(Locale locale) {
        this.locale = locale;
    }
}
